package auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.User;

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.json.JsonObject;

/**
 * Servlet implementation class Apitest
 */
public class Apitest extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Apitest() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String apiKey = getServletConfig().getInitParameter("API_KEY");
		String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
		HttpSession session = request.getSession();
		String sessionKey = (String) session.getAttribute("testApiAppSession");
		String authToken = request.getParameter("auth_token");
		String expires = request.getParameter("expires");
		String code = request.getParameter("code");

		FacebookClient facebookClient = null;

		if (authToken != null && expires !=null) {
			 facebookClient = new DefaultFacebookClient(authToken);
					
			session.setAttribute("testApiAppSession", authToken);
			// SELECT post_id, actor_id, target_id, message FROM stream WHERE source_id = me() AND created_time < 1262196000
			// String query = "SELECT post_id, actor_id, message FROM stream WHERE filter_key in ('others','owner') or source_id=me()";
//			String query = "SELECT post_id, actor_id, target_id, message FROM stream WHERE filter_key in ('others','owner') AND created_time > 1262196000";
//			List<JsonObject> queryResults = facebookClient.executeFqlQuery(query, JsonObject.class);
//			response.getWriter().println(queryResults.size());
//			for (JsonObject post : queryResults) {
//				response.getWriter().println(post.getString("message") + " || ");
//			}
			
			
			//this.authFacebookLogin(authToken, Integer.parseInt(expires));
//			com.restfb.types.User user = facebookClient.fetchObject("me", com.restfb.types.User.class);
////			Connection<com.restfb.types.User> myFriends = facebookClient.fetchConnection("me/friends", com.restfb.types.User.class);
			
			Date oneWeekAgo = new Date(System.currentTimeMillis() - 1000L * 60L * 60L * 24L * 365L);
			response.getWriter().println("Since: " + oneWeekAgo.toString() + " Fin    ");
			
			Connection<com.restfb.types.Post> myFeed = facebookClient.fetchConnection("me/feed", com.restfb.types.Post.class, Parameter.with("since", oneWeekAgo));
			List<com.restfb.types.Post> posts = myFeed.getData();
			response.getWriter().println(myFeed.getNextPageUrl() + " URL ");
//			response.getWriter().println(user.getName());
			response.getWriter().println(posts.size());
			for (com.restfb.types.Post post : posts) {
				response.getWriter().println(post.getMessage() + " ; " + post.getCreatedTime() + " || "); 
				//response.getWriter().println(post.getLikesCount().toString());
			}
//			List<com.restfb.types.User> friends = myFriends.getData();
//			for (com.restfb.types.User friend : friends) {
//				response.getWriter().println(friend.getName()); 
//				//response.getWriter().println(post.getLikesCount().toString());
//			}
			
					
		} else if (code != null) {
//			response.sendRedirect("https://graph.facebook.com/oauth/access_token?client_id="
//					+ apiKey + "&redirect_uri=" + "http://localhost:8080/PoCs/Apitest" + "&client_secret=" + secretKey + "&code=" + code);
			URL url;
			HttpURLConnection conn;
			url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + apiKey + "&redirect_uri=" + "http://localhost:8080/PoCs/Apitest" + "&client_secret=" + secretKey + "&code=" + code);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String in = br.readLine();
			String access_token = in.substring(in.indexOf("access_token=") + "access_token=".length(), in.indexOf("&expires="));
			String expiresTime = in.substring(in.indexOf("&expires=") + "&expires=".length(), in.length());
			response.sendRedirect("http://localhost:8080/PoCs/Apitest?auth_token=" + access_token + "&expires=" + expiresTime);
//			response.sendRedirect("http://graph.facebook.com/oauth/authorize?client_id="
//					+ apiKey + "&redirect_uri=" + "http://localhost:8080/PoCs/Apitest" + "&response_type=token");
			
			return;
		} else {
			// response.sendRedirect("https://www.facebook.com/login.php?api_key="+apiKey);
			response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id="
					+ apiKey + "&redirect_uri=" + "http://localhost:8080/PoCs/Apitest" + "&state=" + "testApiAppSession" + "&scope=user_birthday,read_stream,user_likes,user_relationships");

			return;
		}
		//response.getWriter().println("HelloWorld");
	}
	
	public void authFacebookLogin(String accessToken, int expires) {
//        try {
//            JSONObject resp = new JSONObject("https://graph.facebook.com/me?access_token=" + accessToken);
//
//            String id = resp.getString("id");
//            String firstName = resp.getString("first_name");
//            String lastName = resp.getString("last_name");
//            String email = resp.getString("email");
//
//            // ...
//            // create and authorise the user in your current system w/ data above
//            // ...
//
//        } catch (Throwable ex) {
//            throw new RuntimeException("failed login", ex);
//        }
		
		
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
